﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Microsoft.Win32;
using System.Windows;
using System.Xml;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls;

namespace SHomeWorkshop.LunarMind.Commands
{
    /// <summary>
    /// 以此类为模板，制作自定义命令类
    ///     共需要修改１０处！！！
    /// ==============================
    /// 
    /// 将当前选定标题下移一层（自动添加一个新标题作为上级）。
    /// ★①，修改类名。
    /// </summary>
    public static class MoveToLowerLevelCommand
    {
        private static RoutedUICommand routedUICmd;//创建私有字段

        public static RoutedUICommand RoutedUICmd//创建只读静态属性
        {
            get { return routedUICmd; }
        }

        /// <summary>
        /// ★②，修改静态构造方法名。
        /// </summary>
        static MoveToLowerLevelCommand()//类型构造器
        {
            //★③，修改两个字符串参数名。★④以及第三个参数的类型名。
            routedUICmd = new RoutedUICommand(
                "MoveToLowerLevelCommand",
                "MoveToLowerLevelCommand",
                typeof(MoveToLowerLevelCommand),//创建RoutedUICommand对象
                 new InputGestureCollection() 
                { 
                    //★⑤，修改此处两个参数，以便挂接快捷键。
                    new KeyGesture(Key.Right,ModifierKeys.Alt,"Alt+Right"),
                    new KeyGesture(Key.Down,ModifierKeys.Alt,"Alt+Down"),
                });

            cmdBinding.Command = routedUICmd;
            cmdBinding.CanExecute += new CanExecuteRoutedEventHandler(cmdBinding_CanExecute);
            cmdBinding.Executed += new ExecutedRoutedEventHandler(cmdBinding_Executed);
        }

        private static CommandBinding cmdBinding = new CommandBinding();

        public static CommandBinding CmdBinding
        {
            get { return cmdBinding; }
        }

        static void cmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            //★⑦，修改此方法的实现。

            MoveToLowerLevel();
        }

        /// <summary>
        /// 此方法是调用DeleteCommand的Delete来实现。
        /// </summary>
        internal static void MoveToLowerLevel()
        {
            if (Globals.SelectedTitlesList == null)
            {
                MessageBox.Show("请先选中一个标题！", Globals.AppName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (Globals.SelectedTitlesList.Count != 1)
            {
                MessageBox.Show("请先选中【一个】标题！此操作不支持多选。", Globals.AppName,
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Title curTitle = Globals.SelectedTitlesList[0];

            if (curTitle == Globals.MainWindow.RootTitle)
            {
                MessageBox.Show("根标题不能平移到下一级！", Globals.AppName,
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (curTitle.IsFixed)
            {
                MessageBox.Show("FixedTitle不能平移到下一级！", Globals.AppName,
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            Title higherTitle = curTitle.GetHigherLvelTitle();
            if (higherTitle == null)
            {
                MessageBox.Show("发生意外，没有找到上级标题，无法继续平移！", Globals.AppName,
                       MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            ModifingItem mi = new ModifingItem()
            {
                ModifingName = "平移到下一级",
                IsNeedRefreshTitleAndLinesLocation = true,
                OldSelectedTitleID = curTitle.ID,
            };

            Title newTitle = new Title(Globals.MainWindow);

            XmlNode titleSetNode = Globals.MainWindow.MainXmlDocument.DocumentElement.SelectSingleNode("TitleSet");

            if (titleSetNode == null)
            {
                titleSetNode = Globals.MainWindow.MainXmlDocument.DocumentElement.AppendXml("<TitleSet />");
            }

            if (titleSetNode == null)
            {
                MessageBox.Show("发生意外，没有找到<TitleSet>节点，无法继续平移！", Globals.AppName,
                      MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            double newFontSize = 15;
            if (curTitle.GetHigherLvelTitle().IsRootTitle)
            {
                newFontSize = 18;
            }

            string newXmlText = "<Title ID=\"" + newTitle.ID + "\" HigherLevelTitleID=\"" +
                higherTitle.ID + "\" Index=\"" + curTitle.Index.ToString() +
                "\" Direction=\"" + curTitle.Direction.ToString() + "\">" +
                "<TextSet><Text FontSize=\"" + newFontSize.ToString() +
                "\" FontName=\"Microsoft YaHei\">..新上级标题..</Text></TextSet></Title>";

            XmlNode newNode = titleSetNode.AppendXml(newXmlText);

            newTitle.XmlData = newNode;

            Action actInsertTitle = new Action(newTitle.ID, -1, newTitle.GetType().Name,
                "InsertTitle", null, newTitle.XmlData.OuterXml, ActionType.InsertTitle, higherTitle.ID);

            Globals.MainWindow.mainCanvas.Children.Add(newTitle);

            mi.Add(actInsertTitle);//注意这个顺序。必须先插入新标题才可以引用新标题。

            if (curTitle.Index != 0)
            {
                Action actIndex = new Action(curTitle.ID, -1, curTitle.GetType().Name, "Index", curTitle.Index.ToString(), "0");
                curTitle.Index = 0;
                mi.Add(actIndex);
            }

            Action actHigherID = new Action(curTitle.ID, -1, curTitle.GetType().Name, "HigherLevelTitleID",
                curTitle.HigherLevelTitleID, newTitle.ID);

            curTitle.HigherLevelTitleID = newTitle.ID;

            mi.Add(actHigherID);

            newTitle.SelectOnlySelf();
            mi.NewSelectedTitleID = newTitle.ID;

            Globals.MainWindow.Do(mi);
            Globals.MainWindow.IsModified = true;

            Globals.MainWindow.RefreshTitleAndLinesLocation();

            Globals.MainWindow.TryScrollTitle(newTitle);
        }

        static void cmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            //★⑧，修改此方法的实现。
            if (Globals.SelectedTitlesList == null)
            {
                e.CanExecute = false; return;
            }

            if (Globals.SelectedTitlesList.Count != 1)
            {
                e.CanExecute = false; return;
            }

            Title t = Globals.SelectedTitlesList[0];

            if (t == Globals.MainWindow.RootTitle)
            {
                e.CanExecute = false; return;
            }

            if (t.IsFixed)
            {
                e.CanExecute = false; return;
            }

            e.CanExecute = true; return;//只要不是根标题。且只选中了一个标题。都可以下移一层。
        }
    }
}
